package pers.amos.eshop.advance.inventory.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.amos.eshop.advance.inventory.mapper.ProductInventoryMapper;
import pers.amos.eshop.advance.inventory.model.ProductInventory;
import pers.amos.eshop.advance.inventory.redis.RedisUtils;
import pers.amos.eshop.advance.inventory.service.ProductInventoryService;


@Service
public class ProductInventoryServiceImpl implements ProductInventoryService {

    @Autowired
    private ProductInventoryMapper productInventoryMapper;

    @Autowired
    private RedisUtils redisUtils;

    private final static String PRODUCT_INVENTORY_KEY_PREFIX = "product_inventory_";

    @Override
    public void add(ProductInventory productInventory) {
        Long id = productInventory.getId();
        productInventoryMapper.add(productInventory);

        redisUtils.set(PRODUCT_INVENTORY_KEY_PREFIX + id, productInventory.toString());
    }

    @Override
    public void update(ProductInventory productInventory) {
        Long id = productInventory.getId();
        productInventoryMapper.update(productInventory);

        redisUtils.set(PRODUCT_INVENTORY_KEY_PREFIX + id, productInventory.toString());
    }

    @Override
    public void delete(Long id) {
        productInventoryMapper.delete(id);

        redisUtils.delete(PRODUCT_INVENTORY_KEY_PREFIX + id);
    }

    @Override
    public ProductInventory findById(Long id) {
        return productInventoryMapper.findById(id);
    }

    @Override
    public ProductInventory findByProductId(Long productId) {
        String productInventory = redisUtils.get(PRODUCT_INVENTORY_KEY_PREFIX);
        if (StrUtil.isNotBlank(productInventory)) {
            return JSONUtil.toBean(productInventory, ProductInventory.class);
        }

        return productInventoryMapper.findByProductId(productId);
    }

}
